Skip to main content

Introduction to the DOM

Understanding the Document Object Model (DOM)

The DOM (Document Object Model) is a structured representation of HTML documents that lets JavaScript access and manipulate webpage elements. When a webpage loads, the browser creates a DOM for the page, turning HTML elements into nodes that JavaScript can interact with.

  • DOM Example: Think of the DOM as a tree structure, where each HTML element (like <div>, <p>, etc.) is a “node” in this tree. For example, the HTML below is structured into a DOM with a body node containing a div and p element.
<!DOCTYPE html>
<html lang="en">
<head>
<title>DOM Example</title>
</head>
<body>
<div id="main-container">
<p>Hello, World!</p>
</div>
</body>
</html>

How JavaScript Interacts with HTML & CSS through the DOM

JavaScript can access and manipulate the HTML elements of the DOM to make changes in real-time without reloading the page. This is essential for creating interactive and dynamic web pages.

  • JavaScript Example: Here’s how JavaScript can change the text inside the <p> element in the HTML example above.

    // Select the <p> element
    const paragraph = document.querySelector("#main-container p");

    // Change the text content
    paragraph.textContent = "Hello, DOM!";

    Explanation: document.querySelector("#main-container p") finds the first <p> element inside the <div> with the ID main-container, then .textContent is used to change the text.

Setting up Your Development Environment

For practicing DOM manipulation, you'll need a code editor (like Visual Studio Code) and a browser (e.g., Chrome, Firefox). Here's a setup to get you started quickly:

  1. Create an HTML file (e.g., index.html), then add a script tag to include JavaScript:

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <title>DOM Manipulation</title>
    </head>
    <body>
    <div id="content">
    <p>Welcome to the DOM!</p>
    <button id="change-text">Change Text</button>
    </div>
    <script src="script.js"></script> <!-- External JavaScript file -->
    </body>
    </html>
  2. Write the JavaScript code in a file named script.js:

    // Select the button element
    const button = document.getElementById("change-text");

    // Add an event listener to the button to change text on click
    button.addEventListener("click", function() {
    const paragraph = document.querySelector("#content p");
    paragraph.textContent = "Text changed via JavaScript!";
    });
  3. Run the HTML file in your browser. You should see a button, and when clicked, it changes the text in the paragraph.